var api = require('../../utils/api.js');
var app = getApp();
import jiuaiDebounce from '../../utils/jiuai-debounce.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    disIdxArr:[],//折扣下标数组
   // discontArr:[1,2,3],
    list:[],
    total:0
  },
  toAddress(){
    wx.navigateTo({
      url: "/pages/address/address?page=FillOrder",
    })
  },
  bindPickerChange (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var disIdxArr = this.data.disIdxArr;
    disIdxArr[e.currentTarget.dataset.idx] = e.detail.value
    this.setData({
      disIdxArr
    })
    this.getTotal()
  },

  //获取商品列表
  getGoodsList(){
    let disIdxArr = this.data.disIdxArr;
    let params = {
      token: wx.getStorageSync('token'),
      user_address: wx.getStorageSync('receiveAds') || {},
      list: this.data.selectList
    }
    api.fetchApi('/order/settle_now', params).then(res=>{
      res.list.forEach((item,index)=>{
        disIdxArr.push(0)
      })
      console.log(disIdxArr)
      this.setData({
        list:res,
        disIdxArr
      })
      this.getTotal();
    })
  },

  //计算总价
  getTotal(){
  let list=this.data.list;
   let total= list.list.reduce((prev, cur,index)=>{
     return prev + ((cur.goods_total_price / 1) * (cur.user_discount[this.data.disIdxArr[index]].value/10))*(cur.fixed_discount / 10) + cur.freight / 1
    },0)
    console.log(total)
    this.setData({
      total
    })
  },

  //提交订单
  confirmOrder(){
    jiuaiDebounce.canDoFunction({
      key: "tap",//基于此值判断是否可以操作，如两个方法传入了同样的key，则会混淆，建议传入调用此事件的方法名，简单好梳理
      time: 5000,//如果传入time字段，则为定时器后，自动解除锁定状态，单位（毫秒）
      success: () => {//成功中调用应该操作的方法，被锁定状态不会执行此代码块内的方法
        wx.showLoading({
          mask: true
        })

        let list = this.data.list;
        list.total_price = this.data.total;
        list.type = this.data.type;

        list.list.forEach((item, index) => {
          item.product_price = ((item.goods_total_price / 1) * (item.user_discount[this.data.disIdxArr[index]].value / 10))*(item.fixed_discount / 10) + item.freight / 1,
            item.user_discount_id = item.user_discount[this.data.disIdxArr[index]].id
        })
        // console.log(list)
        let params = {
          token: wx.getStorageSync('token'),
          list
        }
        api.fetchApi('/Payment/create_order', params).then(res => {
          let { nonceStr, package: package1, paySign, signType, timeStamp } = res

          wx.requestPayment({
            timeStamp,
            nonceStr,
            package: package1,
            signType,
            paySign,
            success: (req) => {
              wx.showToast({
                title: '支付成功',
              })
              setTimeout(() => {
                wx.navigateTo({
                  url: '/pages/myOrder/myOrder?page=FillOrder'
                })
              }, 1000)
            },
            fail: (err) => {
              wx.showToast({
                title: '支付失败',
                icon: 'none'
              })
              setTimeout(() => {
                wx.navigateTo({
                  url: '/pages/myOrder/myOrder?page=FillOrder'
                })
              }, 1000)
            }
          })
        })
       
      }
    })


   
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let selectList = JSON.parse(options.selectList);
    let type = options.type
    this.setData({
      selectList,
      type
    })
    this.getGoodsList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})